import axios from 'axios'
import router from '@/router/router'
import store from '@/vuex/store'
import * as types from '@/vuex/mutation-types'
axios.defaults.timeout = 50000
// axios.defaults.withCredentials = true//发送到服务端的数据带上cookies ，防止服务端sessionID不一致的问题
// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      // config.headers.token = store.state.token
    }
    return config;
  },
  err => {
    return Promise.reject(err)
  });

// http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.code&&response.data.code=='401'){//401权限问题
      store.commit(types.LOGOUT)
      router.replace({
        path: '/',
        query: { redirect: router.currentRoute.fullPath }
      })
    }else return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          store.commit(types.LOGOUT)
          router.replace({
            path: '/',
            query: { redirect: router.currentRoute.fullPath }
          })
      }
    }
    return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  });

export default axios